<!-- 表格个性设置 -->
<template>
  <div class="sh-fields" title="列表个性设置" :class="tbId">
    <slot></slot>

    <el-tooltip v-if="showSeledInfo" effect="dark" content="点击清空表格选中行" placement="top">
      <el-button 
        type="primary" plain
        @click="clearAllSeledRows">
        已选中 <b>{{getSeledRowLen}} 条</b>
      </el-button>
    </el-tooltip>

    <el-popover 
      placement="left"
      width="100"
      trigger="click">
      <div class="cols-set">
        <div class="btns">
          <el-button-group>
            <el-tooltip effect="dark" placement="bottom">
              <p slot="content">注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！</p>
              <el-button type="primary" icon="el-icon-warning-outline"></el-button>
            </el-tooltip>
            <el-button title="重置" type="primary" icon="el-icon-refresh-right" @click="resetTableSet"></el-button>
            <el-button title="保存" type="primary" icon="el-icon-check" @click="saveTableSet">保存</el-button>
          </el-button-group>
        </div>
        <div class="col-items">
          <el-checkbox 
            v-for="col in fields"
            :key="col.field"
            :title="col.label.length > 8 ? col.label : ''"
            :label="col.label" 
            border
            :disabled="col.disabled ? true : false"
            :class="col.disabled ? '' : 'drag-it'"
            v-model="col.show">
          </el-checkbox>
        </div>
      </div>
      
      <i class="el-icon-s-tools tb-col-oper" slot="reference"></i>
    </el-popover>
  </div>
</template>

<script>
import Sortable from "sortablejs";

import * as commService from "@/api/services/common.service";

export default {
  name: "TabelSelfSet",
  props: {
    // 表格名称
    tbTitle: {
      require: true,
      type: String,
      default: "",
    },
    // 表格数据参数对象名称
    dgName: {
      require: true,
      type: String,
      default: "dg",
    },
    // 表格唯一id
    tbId: {
      require: true,
      type: String,
      default: "",
    },
    // 表格列数据源
    srcCols: {
      require: true,
      type: Array,
      default: [],
    },
    // 表格当前显示列列表
    columns: {
      require: true,
      type: Array,
      default: [],
    },
    // 是否显示表格选中
    showSeledInfo: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      oldCols: this.U.scopy(this.srcCols), // 保存原始的列数据
      cols: this.U.scopy(this.columns), // 当前表格所有显示列数组
      fields: this.U.scopy(this.columns), // 表格原所有列数组
    };
  },
  computed: {
    // 选中行条数
    getSeledRowLen(){
      const tbThat = this.showSeledInfo;
      if(tbThat){
        return tbThat[this.dgName].selRows.length;
      }else{
        return 0;
      }
    },
  },
  watch: {
    // 监控表格列数组数据变化
    columns: {
      handler(c) {
        const that = this;

        // 当父组件的数据改变时，需要同步到子组件
        that.cols = that.U.scopy(c);
      },
      deep: true, // true=深度监听
    },
    // 监控-字段数组数据变化
    fields: {
      handler(arr) {
        const that = this;

        let cols = that.U.scopy(arr);
        let list = cols.filter((it) => { return it.show; });
        if(list.length < 1) {
          that.U.qerror('列表至少需保留一项');
        }else{
          that.$emit("saveSet", { dgName: that.dgName, cols: list });
        }
      },
      deep: true,
    },
    oldCols: {
      handler(arr) {

      },
      deep: true,
    },
  },
  mounted() {
    let that = this;

    // console.log('传入的拖动列', that.fields);
    // console.log('传入的表格列', that.cols);

    setTimeout(() => {
      that.columnDrop();
    }, 500);
    getalllist()
  },
  created() {
    const that = this;

    let tbSet = sessionStorage.getItem(that.tbId);
    if (tbSet) that.fields = JSON.parse(tbSet);
  },
  methods: {
    /** 列拖拽 */
    columnDrop() {
      const that = this;

      const el = document.querySelector(`.${that.tbId} .cols-set .col-items`);
      Sortable.create(el, {
        draggable: '.drag-it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
          const targetRow = that.fields.splice(evt.oldIndex, 1)[0];
          that.fields.splice(evt.newIndex, 0, targetRow);
          
          // 重新赋值给列数组
          // let cols = that.U.scopy(that.fields);
          // let list = cols.filter(it => { return it.show; });
          // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
      });
    },
    // 重置表格设置
    resetTableSet() {
      const that = this,
        U = that.U;

      Array.isArray(that.oldCols) &&
        that.oldCols.forEach((it) => {
          it.show = true;
        });
      that.fields = U.scopy(that.oldCols);

      let loading = U.qloading("数据请求中...");
      commService
        .setTabelSet({ tbNum: that.tbId, dat: "" })
        .then((res) => {
          U.qclose(loading);

          if (!res || res.code != 1) {
            U.qerror(res.msg);
          } else {
            sessionStorage.removeItem(that.tbId);

            U.qsuccess("表格设置成功");
          }
        })
        .catch(() => {
          U.qclose(loading);
        });
    },
    // 保存表格设置
    saveTableSet() {
      const that = this,
        U = that.U;

      // 最终保存的是显示/隐藏-表格列数组的字符串至数据库
      let map = {};
      Array.isArray(that.cols) &&
        that.cols.forEach((it) => {
          map[it.field] = it;
        });

      Array.isArray(that.fields) &&
        that.fields.forEach((it) => {
          let col = map[it.field];
          // 重新赋值列宽度
          if (col) it.width = col.width;
        });

      let loading = U.qloading("数据请求中...");
      let ps = {
        tbNum: that.tbId,
        tbName: that.tbTitle,
        dat: JSON.stringify(that.fields),
      };
      commService
        .setTabelSet(ps)
        .then((res) => {
          U.qclose(loading);

          if (!res || res.code != 1) {
            U.qerror(res.msg);
          } else {
            sessionStorage.setItem(that.tbId, JSON.stringify(that.fields));

            U.qsuccess("表格设置成功");
          }
        })
        .catch(() => {
          U.qclose(loading);
        });
    },
    // 清空所有选中行
    clearAllSeledRows(){
      const tbThat = this.showSeledInfo;
      tbThat.$refs[tbThat[this.dgName].tbName].clearSelection();
    },

    getalllist() {
      const that = this,
        U = that.U;
      commService
        .setTabelSet({ tbNum: that.tbId, dat: "" })
        .then((res) => {
          U.qclose(loading);

          if (!res || res.code != 1) {
            U.qerror(res.msg);
          } else {
            sessionStorage.removeItem(that.tbId);

            U.qsuccess("表格设置成功");
          }
        })
        .catch(() => {
          U.qclose(loading);
        });
    },


  },
};
</script>

<style lang="less">
.tb-col-oper{
  margin-left: 10px;
}

.sh-fields{
  cursor: pointer;
}

/* 列-显示/隐藏 */
.cols-set{
  line-height: 35px;
  max-height: 60vh;
  overflow-y: auto;
  overflow-x: hidden;

  .btns .el-button-group{
    display: flex;

    button:not(:first-child){
      flex: 1;
    }
  }

  .col-items > label{
    margin-left: 0px !important;
    margin: 0px;
    width: 100%;
  }

  .sortable-ghost {
    color: #fff !important;
    background: #efefef !important;
  }
}
.cols-set::-webkit-scrollbar {
  width: 5px !important;
}

</style>
